﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Workflow.Application.IService;
using Workflow.Domain.Models;
using Workflow.Infrastructure.IRepository;
using WorkflowCore.Interface;

namespace Workflow.Application.Extend
{
    public static class WorkflowExtend
    {
        // 作用：项目启动时注册流程
        public static void UseWorkflow(this WebApplication app)
        {
            var host = app.Services.GetService<IWorkflowHost>();

            // 项目启动时，执行
            app.Lifetime.ApplicationStarted.Register(() =>
            {
                host.Start(); // 开启流程引擎主机

                var scope = app.Services.CreateScope().ServiceProvider;
                var definitionRepository = scope.GetService<IBaseRepository<WorkflowDefinitionModel>>();
                var workflowService = scope.GetService<IWorkflowService>();

                var list = definitionRepository.GetAll();
                // foreach 会执行IQueryable，相当于执行数据库
                foreach (var i in list)
                {
                    workflowService.LoadDefinition(i);
                }
            });

            // 项目结束时，执行
            app.Lifetime.ApplicationStopping.Register(() =>
            {
                host.Stop(); // 停止流程引擎主机
            });
        }
    }
}
